package com.base.system.controller;

import com.base.system.base.http.HttpResult;
import com.base.system.base.http.socket.WebSocket;
import com.base.system.bean.MsgInfo;
import com.base.system.config.security.AuthUser;
import com.base.system.config.security.UserKit;
import com.base.system.jpa.entity.JpaUser;
import com.base.system.jpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.Optional;

@RestController
public class TestController {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    WebSocket webSocket;

    @GetMapping
    public HttpResult<AuthUser> test() {
        Optional<AuthUser> currentUser = UserKit.getCurrentUser();
        Optional<JpaUser> byId = userRepository.findById(currentUser.get().getId());
        return HttpResult.ok(byId.get());
    }

    @GetMapping("/index")
    @PreAuthorize("hasAuthority('user_index')")
    public String index() {
        System.err.println("我的主页");
        return "我的个人主页";
    }

    @GetMapping("/test")
    @PreAuthorize("hasAuthority('user_test')")
    public String test1(Principal principal) {
        System.err.println("我的测试" + principal.getName());
        return "我的测试页面";
    }

    @GetMapping("/test2")
    public String test2() {
        System.err.println("我的测试2");
        return "我的测试页面";
    }

    @GetMapping("/sendMany")
    public HttpResult<Void> greeting(String msg) {
        System.err.println(msg);
        webSocket.sendAllMessage("群发：" + msg);
        return HttpResult.ok();
    }

    /**
     * 单聊
     */
    @GetMapping("/chat")
    public HttpResult<Void> chat(String user, String msg) {
        System.err.println(msg);
        webSocket.sendObjMessage(user, new MsgInfo().setContent("这是测试发送").setFrom("小木").setTo(user));
        return HttpResult.ok();
    }
}
